import Koa from 'koa';
import route from 'koa-route';
import koaBody from 'koa-body';
import nodemailer from 'nodemailer';
import fs from 'fs';
import path from 'path';
import TransporterArguments from './interfaces/TransporterArguments';

const app = new Koa();
// 创建一个邮件传输器
const transporterArguments: TransporterArguments = JSON.parse(
  fs.readFileSync(path.join(__dirname, 'conf', 'mail.conf.json')).toString()
);

const transporter = nodemailer.createTransport(transporterArguments);
// 解析 Request body 到 ctx.request.body
app.use(koaBody());

// 跨域
app.use(async (ctx, next) => {
  if (ctx.headers.origin) {
    ctx.set({
      'Access-Control-Allow-Origin': ctx.headers.origin,
      'Access-Control-Allow-Methods': 'POST'
      // 'Access-Control-Allow-Methods': 'POST, DELETE, PUT, GET, OPTIONS',
    });
  }
  await next();
});

// 允许 OPTIONS
app.use(async (ctx, next) => {
  if (ctx.method === 'OPTIONS') {
    ctx.status = 204;
    ctx.set({
      'Access-Control-Allow-Methods': 'POST',
      'Access-Control-Allow-Headers': 'content-type'
    });
  }
  await next();
});

// /mail
app.use(
  route.post('/mail', async ctx => {
    const {
      to,
      subject,
      text,
      html
    }: {
      to: string;
      subject: string;
      text: string;
      html: string;
    } = ctx.request.body;

    // 参数校验
    if (
      undefined === to ||
      undefined === subject ||
      (undefined === text && undefined === html)
    ) {
      ctx.status = 400;
      ctx.body = {
        to,
        subject,
        text,
        html
      };
      return;
    }

    // 发送邮件
    transporter.sendMail({
      from: transporterArguments.auth.user,
      to,
      subject,
      text,
      html
    });
    ctx.status = 204;
  })
);

app.listen(3000, () => {
  console.log('📧 dvoa_mail-service ok!');
});
